<template>
  <div class="homework-generator">
    <div class="layout-container">
      <!-- 侧边栏 -->
      <!-- <div class="sidebar">
        <div class="sidebar-header">
          <h3>习题管理</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="generator">
            <el-icon><Edit /></el-icon>
            <span>习题定制</span>
          </el-menu-item>
          <el-menu-item index="history">
            <el-icon><List /></el-icon>
            <span>历史记录</span>
          </el-menu-item>
          <el-menu-item index="hot">
            <el-icon><Star /></el-icon>
            <span>热点考题</span>
          </el-menu-item>
          <el-menu-item index="mistakes">
            <el-icon><Warning /></el-icon>
            <span>高频错题</span>
          </el-menu-item>
        </el-menu>
      </div> -->

      <!-- 主内容区 -->
      <div class="main-content">
      

        <!-- 习题生成区域 -->
        <div class="generator-section">
          <el-card class="generator-card">
            <template #header>
              <div class="card-header">
                <h2>智能习题生成</h2>
              </div>
            </template>
            
            <el-form :model="form" label-width="120px" class="generator-form">
              <div class="form-row">
                <el-form-item label="教学阶段">
                  <el-select v-model="form.stage" placeholder="请选择教学阶段" @change="handleStageChange">
                    <el-option label="小学" value="primary" />
                    <el-option label="初中" value="junior" />
                    <el-option label="高中" value="senior" />
                    <el-option label="大学" value="university" />
                  </el-select>
                </el-form-item>

                <el-form-item label="教学科目">
                  <el-select v-model="form.subject" placeholder="请选择教学科目">
                    <el-option
                      v-for="subject in availableSubjects"
                      :key="subject.value"
                      :label="subject.label"
                      :value="subject.value"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="年级">
                  <el-select v-model="form.grade" placeholder="请选择年级">
                    <el-option
                      v-for="grade in availableGrades"
                      :key="grade.value"
                      :label="grade.label"
                      :value="grade.value"
                    />
                  </el-select>
                </el-form-item>
              </div>

              <div class="form-row">
                <el-form-item label="知识点">
                  <el-input
                    v-model="form.knowledge"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入知识点，多个知识点用逗号分隔"
                  />
                </el-form-item>
                
                <el-form-item label="难度等级">
                  <el-select v-model="form.difficulty" placeholder="请选择难度等级">
                    <el-option label="简单" value="easy" />
                    <el-option label="中等" value="medium" />
                    <el-option label="困难" value="hard" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="题目数量">
                  <el-input-number v-model="form.count" :min="1" :max="20" />
                </el-form-item>
              </div>
              
              <el-form-item label="题目类型">
                <el-checkbox-group v-model="form.types" class="type-checkbox-group">
                  <el-checkbox value="选择题">选择题</el-checkbox>
                  <el-checkbox value="填空题">填空题</el-checkbox>
                  <el-checkbox value="简答题">简答题</el-checkbox>
                  <el-checkbox value="计算题">计算题</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="handleGenerateHomework" :loading="loading" class="generate-btn">
                  生成习题
                </el-button>
                <el-button type="success" @click="fetchExistingExercises" :loading="fetchingExercises">
                  查询习题库
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </div>

        <!-- 新增文本框显示模型返回值 -->
        <el-card v-if="modelResponse" class="model-response-card">
          <template #header>
            <div class="card-header">
              <h3>大模型原始输出</h3>
            </div>
          </template>
          <pre class="model-response-content">{{ modelResponse }}</pre>
        </el-card>

        <!-- 数据库习题列表 -->
        <div v-if="databaseExercises.length > 0 && activeTab === 'generator'" class="database-exercises-section">
          <el-card class="database-exercises-card">
            <template #header>
              <div class="card-header">
                <h2>习题库中的习题</h2>
                <div class="card-actions">
                  <el-button type="success" size="small" @click="selectAllExercises">
                    全选
                  </el-button>
                  <el-button type="primary" size="small" @click="createHomeworkFromSelected" :disabled="selectedExercises.length === 0">
                    生成作业
                  </el-button>
                </div>
              </div>
            </template>
            
            <div class="exercises-container">
              <el-table
                :data="databaseExercises"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="55"
                />
                <el-table-column
                  label="题型"
                  prop="questionType"
                  width="120"
                >
                  <template #default="scope">
                    {{ formatQuestionType(scope.row.questionType) }}
                  </template>
                </el-table-column>
                <el-table-column
                  label="内容"
                  prop="content"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="难度"
                  prop="difficulty"
                  width="100"
                />
                <el-table-column
                  label="知识点"
                  prop="topic"
                  width="150"
                  show-overflow-tooltip
                />
                <el-table-column
                  label="操作"
                  width="120"
                >
                  <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="viewExerciseDetail(scope.row)"
                    >
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <!-- 生成的习题展示区域 -->
    <div v-if="generatedQuestions.length > 0" class="questions-section">
      <div class="section-header">
        <h3>生成的习题</h3>
        <el-button type="primary" @click="saveToHistory">保存到历史记录</el-button>
      </div>
      <el-card v-for="(question, index) in generatedQuestions" :key="index" class="question-card">
        <template #header>
          <div class="question-header">
            <span>【{{ getQuestionType(question) }}】问题{{ index + 1 }}</span>
            <el-tag size="small" :type="getDifficultyType(question.difficulty)">
              {{ getDifficultyLabel(question.difficulty) }}
            </el-tag>
          </div>
        </template>
        <div class="question-content">
          <p class="question-text">{{ question.content }}</p>
          
          <!-- 选择题选项 -->
          <div v-if="question.options" class="question-options">
            <p v-if="Array.isArray(question.options)" v-for="(option, optIndex) in question.options" :key="optIndex">
              {{ ['A', 'B', 'C', 'D'][optIndex] }}. {{ option }}
            </p>
            <p v-else v-for="(option, key) in question.options" :key="key">
              {{ key }}. {{ option }}
            </p>
          </div>
          
          <!-- 填空题 -->
          <div v-if="getQuestionType(question) === '填空题'" class="question-blanks">
            <p v-html="formatBlankQuestion(question.content)"></p>
          </div>
          
          <div class="question-answer">
            <!-- 填空题答案 -->
            <div v-if="getQuestionType(question) === '填空题' && Array.isArray(question.answer)">
              <p><strong>答案：</strong></p>
              <p v-for="(ans, ansIndex) in question.answer" :key="ansIndex">
                空{{ ansIndex + 1 }}：{{ ans }}
              </p>
            </div>
            <!-- 其他题型答案 -->
            <p v-else><strong>答案：</strong>{{ question.answer }}</p>
            
            <!-- 解析部分 -->
            <div v-if="question.explanation" class="question-explanation">
              <p><strong>解析：</strong></p>
              <p v-html="formatExplanation(question.explanation)"></p>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, List, Document, Star, Warning, ChatDotRound, UploadFilled, Refresh } from '@element-plus/icons-vue'
import { generateHomework, saveHomework, chatGenerateHomework } from '@/api/homework'
import { useRouter } from 'vue-router'
import { exerciseApi } from '@/api'

const router = useRouter()

const activeTab = ref('generator')
const form = ref({
  stage: '',
  subject: '',
  grade: '',
  knowledge: '',
  difficulty: 'medium',
  count: 5,
  types: ['选择题', '填空题']
})

const loading = ref(false)
const chatLoading = ref(false)
const generatedQuestions = ref([])
const chatMessages = ref([])
const chatInput = ref('')
const chatMessagesRef = ref(null)

const activeMenu = ref('generator')
const chatHistory = ref([])
const currentChatId = ref(null)

const modelResponse = ref('')
const fetchingExercises = ref(false)
const databaseExercises = ref([])
const selectedExercises = ref([])

const historyList = ref([])
const loadingHistory = ref(false)

// 科目选项
const subjects = {
  primary: [
    { label: '语文', value: 'chinese' },
    { label: '数学', value: 'math' },
    { label: '英语', value: 'english' }
  ],
  junior: [
      { label: '语文', value: 'chinese' },
      { label: '数学', value: 'math' },
      { label: '英语', value: 'english' },
      { label: '科学', value: 'science' },
      { label: '社会', value: 'society' }
    ],
  senior: [
    { label: '语文', value: 'chinese' },
    { label: '数学', value: 'math' },
    { label: '英语', value: 'english' },
    { label: '物理', value: 'physics' },
    { label: '化学', value: 'chemistry' },
    { label: '生物', value: 'biology' }
  ],
  university: [
    { label: '高等数学', value: 'advanced_math' },
    { label: '大学物理', value: 'university_physics' },
    { label: '大学化学', value: 'university_chemistry' }
  ]
}

// 年级选项
const grades = {
  primary: [
    { label: '一年级', value: 'grade1' },
    { label: '二年级', value: 'grade2' },
    { label: '三年级', value: 'grade3' },
    { label: '四年级', value: 'grade4' },
    { label: '五年级', value: 'grade5' },
    { label: '六年级', value: 'grade6' }
  ],
  junior: [
    { label: '初一', value: 'grade7' },
    { label: '初二', value: 'grade8' },
    { label: '初三', value: 'grade9' }
  ],
  senior: [
    { label: '高一', value: 'grade10' },
    { label: '高二', value: 'grade11' },
    { label: '高三', value: 'grade12' }
  ],
  university: [
    { label: '大一', value: 'university1' },
    { label: '大二', value: 'university2' },
    { label: '大三', value: 'university3' },
    { label: '大四', value: 'university4' }
  ]
}

const availableSubjects = ref([])
const availableGrades = ref([])

const handleStageChange = (stage) => {
  form.value.subject = ''
  form.value.grade = ''
  availableSubjects.value = subjects[stage] || []
  availableGrades.value = grades[stage] || []
}

const handleGenerateHomework = async () => {
  if (!form.value.stage || !form.value.subject || !form.value.grade) {
    ElMessage.warning('请选择教学阶段、科目和年级')
    return
  }

  if (!form.value.knowledge || !form.value.difficulty || !form.value.count) {
    ElMessage.warning('请选择知识点、难度和题目数量')
    return
  }

  if (!form.value.types || form.value.types.length === 0) {
    ElMessage.warning('请至少选择一种题目类型')
    return
  }

  loading.value = true
  try {
    const response = await generateHomework({
      stage: form.value.stage,
      subject: form.value.subject,
      grade: form.value.grade,
      knowledgePoint: form.value.knowledge,
      difficultyLevel: form.value.difficulty,
      questionCount: parseInt(form.value.count),
      questionTypes: form.value.types
    })
    
    // 提取并显示大模型的原始响应
    if (response.originalResponse) {
      modelResponse.value = response.originalResponse
    } else if (response.data && response.data.originalResponse) {
      modelResponse.value = response.data.originalResponse
    } else {
      // 将JSON格式转换为易读的文本格式
      try {
        const data = response.data || response;
        if (typeof data === 'string') {
          // 如果是直接的文本格式，已经是按照题型格式化的，直接显示
          modelResponse.value = data;
          
          // 尝试解析文本中的JSON，这可能是从后端返回的习题数组
          try {
            if (data.trim().startsWith('[') && data.trim().endsWith(']')) {
              const parsedQuestions = JSON.parse(data);
              if (Array.isArray(parsedQuestions) && parsedQuestions.length > 0) {
                generatedQuestions.value = parsedQuestions;
                ElMessage.success(`成功解析${parsedQuestions.length}道习题`);
              }
            }
          } catch (parseError) {
            console.warn('无法解析返回的习题JSON: ', parseError);
            // 解析失败不影响显示原始文本
          }
        } else {
          // 如果是JSON对象，提取并组织关键信息
          let formattedResponse = '大模型生成结果：\n\n';
          
          if (data.content || data.message) {
            formattedResponse += data.content || data.message;
          } else if (data.exercises || data.questions) {
            const questions = data.exercises || data.questions || [];
            questions.forEach((q, index) => {
              // 添加题型标记和题号
              formattedResponse += `【${q.type || '习题'}】问题${index + 1}：${q.content || q.question || ''}\n`;
              
              // 处理选择题选项
              if (q.options) {
                if (Array.isArray(q.options)) {
                  formattedResponse += '\n';
                  q.options.forEach((opt, idx) => {
                    formattedResponse += `${['A', 'B', 'C', 'D'][idx]}：${opt}  `;
                    // 每两个选项换行
                    if (idx % 2 === 1) formattedResponse += '\n';
                  });
                  if (q.options.length % 2 === 1) formattedResponse += '\n';
                } else if (typeof q.options === 'object') {
                  formattedResponse += '\n';
                  const optKeys = Object.keys(q.options).sort();
                  optKeys.forEach((key, idx) => {
                    formattedResponse += `${key}：${q.options[key]}  `;
                    // 每两个选项换行
                    if (idx % 2 === 1) formattedResponse += '\n';
                  });
                  if (optKeys.length % 2 === 1) formattedResponse += '\n';
                }
              }
              
              // 处理答案
              if (q.type === '填空题' && Array.isArray(q.answer)) {
                formattedResponse += '\n答案：\n';
                q.answer.forEach((ans, idx) => {
                  formattedResponse += `空${idx + 1}：${ans}\n`;
                });
              } else {
                formattedResponse += `\n答案：${q.answer || '未提供'}\n`;
              }
              
              // 处理解析
              if (q.explanation) {
                formattedResponse += `\n解析：${q.explanation}\n`;
              }
              
              formattedResponse += '\n----------------------------\n\n';
            });
          } else {
            formattedResponse += JSON.stringify(data, null, 2);
          }
          
          modelResponse.value = formattedResponse;
        }
      } catch (error) {
        console.error('格式化响应失败:', error);
        modelResponse.value = typeof response === 'string' ? response : JSON.stringify(response, null, 2);
      }
    }
    
    if (response.exercises) {
      generatedQuestions.value = response.exercises
    } else if (response.data && response.data.exercises) {
      generatedQuestions.value = response.data.exercises
    } else {
      generatedQuestions.value = response.data ? response.data.questions || [] : []
    }
    
    ElMessage.success('习题生成成功')
  } catch (error) {
    console.error('生成习题失败:', error)
    ElMessage.error('生成习题失败，请重试')
  } finally {
    loading.value = false
  }
}

const sendMessage = async () => {
  if (!chatInput.value.trim()) return
  
  const currentTime = new Date().toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
  
  chatMessages.value.push({
    type: 'user',
    content: chatInput.value,
    time: currentTime
  })
  
  const userMessage = chatInput.value
  chatInput.value = ''
  chatLoading.value = true
  
  try {
    const response = await chatGenerateHomework({
      message: userMessage
    })
    
    // 提取并显示大模型的原始响应
    if (response.originalResponse) {
      modelResponse.value = response.originalResponse
    } else if (response.data && response.data.originalResponse) {
      modelResponse.value = response.data.originalResponse
    } else {
      // 将JSON格式转换为易读的文本格式
      try {
        const data = response.data || response;
        if (typeof data === 'string') {
          // 如果是直接的文本格式，已经是按照题型格式化的，直接显示
          modelResponse.value = data;
        } else {
          // 如果是JSON对象，提取并组织关键信息
          let formattedResponse = '大模型生成结果：\n\n';
          
          if (data.reply || data.content || data.message) {
            formattedResponse += data.reply || data.content || data.message;
          } else if (data.questions || data.exercises) {
            const questions = data.questions || data.exercises || [];
            questions.forEach((q, index) => {
              // 添加题型标记和题号
              formattedResponse += `【${q.type || '习题'}】问题${index + 1}：${q.content || q.question || ''}\n`;
              
              // 处理选择题选项
              if (q.options) {
                if (Array.isArray(q.options)) {
                  formattedResponse += '\n';
                  q.options.forEach((opt, idx) => {
                    formattedResponse += `${['A', 'B', 'C', 'D'][idx]}：${opt}  `;
                    // 每两个选项换行
                    if (idx % 2 === 1) formattedResponse += '\n';
                  });
                  if (q.options.length % 2 === 1) formattedResponse += '\n';
                } else if (typeof q.options === 'object') {
                  formattedResponse += '\n';
                  const optKeys = Object.keys(q.options).sort();
                  optKeys.forEach((key, idx) => {
                    formattedResponse += `${key}：${q.options[key]}  `;
                    // 每两个选项换行
                    if (idx % 2 === 1) formattedResponse += '\n';
                  });
                  if (optKeys.length % 2 === 1) formattedResponse += '\n';
                }
              }
              
              // 处理答案
              if (q.type === '填空题' && Array.isArray(q.answer)) {
                formattedResponse += '\n答案：\n';
                q.answer.forEach((ans, idx) => {
                  formattedResponse += `空${idx + 1}：${ans}\n`;
                });
              } else {
                formattedResponse += `\n答案：${q.answer || '未提供'}\n`;
              }
              
              // 处理解析
              if (q.explanation) {
                formattedResponse += `\n解析：${q.explanation}\n`;
              }
              
              formattedResponse += '\n----------------------------\n\n';
            });
          } else {
            formattedResponse += JSON.stringify(data, null, 2);
          }
          
          modelResponse.value = formattedResponse;
        }
      } catch (error) {
        console.error('格式化响应失败:', error);
        modelResponse.value = typeof response === 'string' ? response : JSON.stringify(response, null, 2);
      }
    }
    
    chatMessages.value.push({
      type: 'ai',
      content: response.data.reply,
      time: new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    })
    
    // 如果AI生成了习题，添加到生成结果中
    if (response.data.questions) {
      generatedQuestions.value = response.data.questions
    }
    
    // 等待DOM更新后滚动到底部
    await nextTick()
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  } finally {
    chatLoading.value = false
  }
}

const saveToHistory = async () => {
  try {
    await saveHomework({
      stage: form.value.stage,
      subject: form.value.subject,
      grade: form.value.grade,
      knowledge: form.value.knowledge,
      questions: generatedQuestions.value
    })
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}

const getDifficultyType = (difficulty) => {
  const types = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

const getDifficultyLabel = (difficulty) => {
  const labels = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return labels[difficulty] || '未知'
}

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'history') {
    router.push('/homework/history')
  }
}

const selectChat = (chat) => {
  currentChatId.value = chat.id
  // TODO: 加载选中对话的消息记录
}

const regenerateMessage = async (index) => {
  const message = chatMessages.value[index]
  // TODO: 实现重新生成逻辑
}

const copyMessage = (content) => {
  navigator.clipboard.writeText(content)
  ElMessage.success('复制成功')
}

const getMenuTitle = (menu) => {
  const titles = {
    generator: '习题定制',
    history: '历史记录',
    hot: '热点考题',
    mistakes: '高频错题'
  }
  return titles[menu] || '未知'
}

const handleUploadSuccess = (response) => {
  ElMessage.success('文件上传成功')
  // TODO: 处理上传成功后的逻辑
}

const handleUploadError = () => {
  ElMessage.error('文件上传失败')
}

const beforeUpload = (file) => {
  const isDoc = file.type === 'application/msword' || 
                file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  const isPdf = file.type === 'application/pdf'
  
  if (!isDoc && !isPdf) {
    ElMessage.error('只能上传 Word 或 PDF 文件!')
    return false
  }
  return true
}

const getQuestionType = (question) => {
  if (!question.type) {
    // 根据题目特征推断题型
    if (question.options) {
      return '选择题'
    } else if (question.content && question.content.includes('___')) {
      return '填空题'
    } else if (question.content && (question.content.includes('计算') || question.content.includes('求解'))) {
      return '计算题'
    } else {
      return '简答题'
    }
  }
  return question.type
}

const formatBlankQuestion = (content) => {
  if (!content) return ''
  // 将填空题中的 ___ 替换为带下划线的空白
  return content.replace(/_{3,}/g, '<span class="blank-line">______</span>')
}

const formatExplanation = (explanation) => {
  if (!explanation) return ''
  // 将解析中的换行符转换为HTML换行
  return explanation.replace(/\n/g, '<br>')
}

// 处理选择习题
const handleSelectionChange = (selection) => {
  selectedExercises.value = selection;
}

// 全选习题
const selectAllExercises = () => {
  // 获取el-table组件实例
  const table = document.querySelector('.el-table__header-wrapper');
  if (table) {
    const checkAll = table.querySelector('.el-checkbox');
    if (checkAll) {
      checkAll.click();
    }
  }
}

// 从选中习题生成作业
const createHomeworkFromSelected = () => {
  if (selectedExercises.value.length === 0) {
    ElMessage.warning('请至少选择一道习题');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要从选中的${selectedExercises.value.length}道习题创建作业吗？`,
    '创建作业',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    // 这里添加创建作业的逻辑
    ElMessage.success(`已成功创建包含${selectedExercises.value.length}道习题的作业`);
  }).catch(() => {
    // 取消操作
  });
}

// 查看习题详情
const viewExerciseDetail = (exercise) => {
  ElMessageBox.alert(
    `<strong>题目内容：</strong>${exercise.content}<br><br>` + 
    (exercise.options ? `<strong>选项：</strong><br>${formatOptions(exercise.options)}<br><br>` : '') +
    `<strong>答案：</strong>${exercise.answer}<br><br>` +
    `<strong>解析：</strong>${exercise.analysis || '无解析'}`,
    `${formatQuestionType(exercise.questionType)} - ${exercise.topic}`,
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  );
}

// 格式化选项
const formatOptions = (options) => {
  if (typeof options === 'string') {
    try {
      options = JSON.parse(options);
    } catch (e) {
      return options;
    }
  }
  
  let result = '';
  for (const key in options) {
    result += `${key}. ${options[key]}<br>`;
  }
  return result;
}

// 格式化题型
const formatQuestionType = (type) => {
  const typeMap = {
    'multiple-choice': '选择题',
    'fill-blank': '填空题',
    'true-false': '判断题',
    'short-answer': '简答题'
  };
  return typeMap[type] || type;
}

// 从数据库获取习题
const fetchExistingExercises = async () => {
  if (!form.subject || !form.grade) {
    ElMessage.warning('请至少选择学科和年级');
    return;
  }
  
  fetchingExercises.value = true;
  try {
    let response;
    if (form.knowledge) {
      // 如果有指定知识点，按条件查询
      response = await exerciseApi.getExercisesByCondition(
        form.subject,
        form.grade,
        form.knowledge
      );
    } else {
      // 否则获取所有符合学科和年级的习题
      response = await exerciseApi.getExercises({
        subject: form.subject,
        grade: form.grade
      });
    }
    
    if (response.data && Array.isArray(response.data)) {
      databaseExercises.value = response.data;
    } else if (response.data && Array.isArray(response.data.data)) {
      databaseExercises.value = response.data.data;
    } else {
      databaseExercises.value = [];
    }
    
    if (databaseExercises.value.length === 0) {
      ElMessage.info('没有找到符合条件的习题，请尝试生成新习题');
    } else {
      ElMessage.success(`找到${databaseExercises.value.length}道符合条件的习题`);
    }
  } catch (error) {
    console.error('获取习题失败:', error);
    ElMessage.error('获取习题失败：' + (error.message || '未知错误'));
    databaseExercises.value = [];
  } finally {
    fetchingExercises.value = false;
  }
}

onMounted(() => {
  // 移除加载历史记录的调用
})
</script>

<style scoped>
.homework-generator {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.layout-container {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 100px);
  align-items: flex-start;
  flex: 1;
}

.sidebar {
  width: 240px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 80px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.sidebar-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tab-switch {
  display: flex;
  justify-content: flex-start;
  padding: 0 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 50px;
  align-items: center;
  margin-bottom: 15px;
  margin-top: -10px;
}

.generator-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.generator-card {
  flex: 2;
  margin-bottom: 0;
}

.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 600px;
}

.chat-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-width: 600px;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 600px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  max-width: 100%;
  margin: 0 auto;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.5;
  word-break: break-word;
}

.message.user {
  align-self: flex-end;
  background-color: #ecf5ff;
  color: #409eff;
}

.message.ai {
  align-self: flex-start;
  background-color: #f4f4f5;
  color: #606266;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  gap: 15px;
  background-color: #fff;
}

.input-area {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.message-input {
  flex: 1;
  min-height: 100px;
  max-height: 200px;
  overflow-y: auto;
  resize: none;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
}

.message-input:focus {
  outline: none;
  border-color: #409eff;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
}

.file-upload {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-upload .el-upload {
  width: auto;
}

.file-upload .el-upload-dragger {
  width: auto;
  height: auto;
  padding: 8px 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.file-upload .el-upload-dragger .el-icon {
  font-size: 16px;
  margin-right: 5px;
}

.file-upload .el-upload-dragger .el-upload__text {
  font-size: 14px;
  color: #606266;
}

.send-button {
  min-width: 100px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  background-color: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.send-button:hover {
  background-color: #66b1ff;
}

.send-button:active {
  background-color: #3a8ee6;
}

.send-button .el-icon {
  font-size: 16px;
}

.send-button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

/* 添加滚动条样式 */
.chat-messages::-webkit-scrollbar,
.message-input::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb,
.message-input::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track,
.message-input::-webkit-scrollbar-track {
  background-color: transparent;
}



.history-card {
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.history-list {
  height: calc(100vh - 180px);
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-subject {
  font-weight: 600;
  color: #303133;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-knowledge {
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 添加滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-track {
  background-color: transparent;
}

.generator-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 0;
}

.generator-card :deep(.el-card__header) {
  padding: 0;
  border-bottom: none;
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: #fff;
}

.generator-card :deep(.el-card__body) {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.chat-layout {
  display: flex;
  gap: 20px;
  height: 100%;
  padding: 20px;
}

.chat-history {
  width: 240px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  height: 100%;
  position: sticky;
  top: 0;
}

.history-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.history-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 4px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.history-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.message-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.content-section {
  height: 100%;
}

.content-placeholder {
  padding: 40px;
  text-align: center;
  color: #909399;
  font-size: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.generator-form {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.type-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.generate-btn {
  width: 200px;
  height: 40px;
  font-size: 16px;
}

.message {
  margin-bottom: 24px;
  max-width: 95%;
  word-wrap: break-word;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message.ai {
  margin-right: auto;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background-color: #409eff;
  color: #fff;
}

.message.ai .message-avatar {
  background-color: #67c23a;
  color: #fff;
}

.message-wrapper {
  flex: 1;
}

.message-content {
  padding: 16px 20px;
  border-radius: 12px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  line-height: 1.6;
  white-space: pre-wrap;
  position: relative;
}

.message.user .message-content {
  background-color: #ecf5ff;
  color: #303133;
  border-top-right-radius: 4px;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.message.ai .message-content {
  background-color: #f5f7fa;
  color: #303133;
  border-top-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.upload-area {
  margin-bottom: 20px;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-area :deep(.el-upload-dragger .el-icon--upload) {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 10px;
}

.upload-area :deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

.upload-area :deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.input-area {
  display: flex;
  gap: 12px;
}

.input-area .el-input {
  flex: 1;
}

.input-area .el-button {
  padding: 0 24px;
  height: 40px;
  align-self: flex-end;
}

/* 添加滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 添加消息时间样式 */
.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  text-align: right;
}

.message.user .message-time {
  text-align: right;
}

.message.ai .message-time {
  text-align: left;
}

.questions-section {
  margin-top: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
}

.section-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.question-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.question-content {
  padding: 20px;
  line-height: 1.6;
}

.question-text {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
}

.question-options {
  margin: 15px 0;
  padding-left: 20px;
}

.question-options p {
  margin: 8px 0;
  color: #606266;
}

.question-answer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.question-answer p {
  margin: 8px 0;
  color: #606266;
}

.question-answer strong {
  color: #303133;
  font-weight: 600;
}

/* 添加遮罩层样式 */
.chat-overlay {
  display: none;
}

.model-response-card {
  margin: 20px 0;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.model-response-content {
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
  color: #303133;
  max-height: 400px;
  overflow-y: auto;
  flex-grow: 1;
}

.model-response-textarea {
  width: 100%;
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.5;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: border-color 0.3s, box-shadow 0.3s;
}

.model-response-textarea:focus {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
  outline: none;
}

.model-response-textarea::placeholder {
  color: #909399; /* 这是 Element Plus 默认的占位符颜色 */
}

/* 填空题的样式 */
.blank-line {
  display: inline-block;
  min-width: 60px;
  border-bottom: 1px solid #606266;
  text-align: center;
  margin: 0 4px;
  position: relative;
  color: #409eff;
  font-weight: bold;
}

/* 题目解析样式 */
.question-explanation {
  background-color: #f8f8f8;
  padding: 12px;
  border-radius: 4px;
  margin-top: 10px;
  border-left: 3px solid #67c23a;
}

.database-exercises-section {
  margin-top: 20px;
}

.database-exercises-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.exercises-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-actions {
  display: flex;
  gap: 10px;
}

/* 表格内容样式优化 */
.el-table {
  --el-table-header-bg-color: #f5f7fa;
  --el-table-row-hover-bg-color: #ecf5ff;
}

.el-table .cell {
  word-break: break-word;
  line-height: 1.5;
}

/* 详情弹窗样式 */
.el-message-box__message p {
  margin: 8px 0;
  line-height: 1.6;
}
</style> 